package www.bwsensing.com.common.netty.decoder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.string.StringDecoder;

import java.nio.charset.Charset;
import java.util.List;

import static www.bwsensing.com.common.utills.StringUtils.bytesToHexString;


/**
 * @author macos-zyj
 */
public class NettyServerDecoder extends StringDecoder {
    private final Charset charset = Charset.defaultCharset();
    private static final String DEFAULT_CHECK_CHARSET =  "GBK";

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
        String message = in.toString(this.charset);
        if (!Charset.forName(DEFAULT_CHECK_CHARSET).newEncoder().canEncode(message)) {
            hexDecode(ctx, in, out);
        } else {
            stringDecode(ctx,in,out);
        }
    }

    protected void hexDecode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) {
        //创建字节数组,buffer.readableBytes可读字节长度
        byte[] b = new byte[buffer.readableBytes()];
        //复制内容到字节数组b
        buffer.readBytes(b);
        //字节数组转字符串
        out.add(bytesToHexString(b));
    }

    protected void stringDecode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) {
        out.add(msg.toString(this.charset));
    }
}
